import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { DownOutlined } from '@ant-design/icons';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Input,
  Table,
  Divider,
  Badge,
  Dropdown,
  Menu,
  Tooltip,
  Popconfirm,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

type IStatusMapType = 'success' | 'error';
const statusMap = ['error', 'success'];
const statusValues = ['禁用', '启用'];

const singleValues = ['否', '是'];

const { pathname } = window.location;

interface LogisticsInfoProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  dataInfo: any;
  checkPerm: any;
  screen: string;
  hasPath: boolean;
}

interface LogisticsInfoState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId: number;
}

@connect(
  ({
    logisticsCenterList: { dataInfo },
    common: { checkPerm },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    checkPerm,
    screen,
    hasPath,
    loading: loading.effects['logisticsCenterList/fetch'],
  }),
)
class LogisticsInfoElem extends React.Component<LogisticsInfoProps, LogisticsInfoState> {
  columns: any = [
    {
      title: '物流中心',
      dataIndex: 'name',
      width: 180,
      ellipsis: true,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditLogisticsCenter(record)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '地址',
      dataIndex: 'address',
      width: 200,
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '营业时间',
      dataIndex: 'serviceTime',
      width: 140,
    },
    {
      title: '电子面单',
      dataIndex: 'electronPageStatus',
      width: 80,
      render: (val: number) => singleValues[val],
    },
    {
      title: '服务电话',
      dataIndex: 'servicePhone',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (val: IStatusMapType) => <Badge status={statusMap[val]} text={statusValues[val]} />,
    },
    {
      title: '分拣机',
      dataIndex: 'sortCount',
      width: 80,
      render: (val: number) => (val ? '有' : '无'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 120,
      fixed: 'right',
      render: (id: number, record: any) => {
        const { checkPerm } = this.props;
        return (
          <>
            {checkPerm.update && (
              <Fragment>
                <span
                  className="operLink"
                  onClick={() => this.handleEditLogisticsCenter(record)}
                >
                  编辑
                </span>
                <Divider type="vertical" />
                <Popconfirm
                  title={`确定要${record.status === 1 ? '禁用' : '启用'}当前物流中心吗？`}
                  onConfirm={() => this.handleConfirm(id, record.status === 1 ? 0 : 1)}
                  className="operLink"
                  okText="确定"
                  cancelText="取消"
                >
                  {record.status === 1 ? '禁用' : '启用'}
                </Popconfirm>
                <Divider type="vertical" />
              </Fragment>
            )}
            <Dropdown arrow overlay={() => this.menu(record)}>
              <span className="operLink">
                更多 <DownOutlined />
              </span>
            </Dropdown>
          </>
        );
      },
    },
  ];

  state: LogisticsInfoState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.verifyPermissions();

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisticsCenterList/fetch',
      payload: this.getQueryParams(),
    });
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => {
    const { checkPerm } = this.props;
    return (
      <Menu>
        {checkPerm.update && (
          <Menu.Item
            className="operLink"
            onClick={() => this.handleConfSort(record.id, record.name)}
          >
            分拣机管理
          </Menu.Item>
        )}
        {checkPerm.operOther && (
          <Menu.Item
            className="operLink"
            onClick={() => this.handleConfCompany(record.id, record.name)}
          >
            配置合作快递公司
          </Menu.Item>
        )}
      </Menu>
    );
  };

  verifyPermissions = () => {
    const addparams = {
      name: 'add',
      oper: 'add',
      resource: 'conf:conf_logis',
    };
    this.fetchAction('common/fetchCheckPerm', addparams);

    const updateparams = {
      name: 'update',
      oper: 'update',
      resource: 'conf:conf_logis',
    };
    this.fetchAction('common/fetchCheckPerm', updateparams);

    const otherparams = {
      name: 'operOther',
      oper: 'list',
      resource: 'conf:delpoy_express',
    };
    this.fetchAction('common/fetchCheckPerm', otherparams);
  };

  /**
   * 添加物流中心
   */
  handleAddLogisticsCenter = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建物流中心',
      url: '/basic/logisticsCenter/list/add',
    });
  };

  /**
   * 编辑物流中心
   */
  handleEditLogisticsCenter = (record: any) => {
    const { id, name, gardenId } = record;
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/logisticsCenter/list/edit?id=${id}&gardenId=${gardenId}`,
    });
  };

  /**
   * 配置快递公司
   */
  handleConfCompany = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `公司${name}`,
      url: `/basic/logisticsCenter/list/express?id=${id}&logisName=${name}`,
    });
  };

  /**
   * 配置分拣机
   */
  handleConfSort = (logisId: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `分拣机${name}`,
      url: `/basic/logisticsCenter/list/sorting?logisId=${logisId}&name=${name}`,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;
      const query = {
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '物流中心',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '物流中心',
      url: pathname,
      isTopMenu: true,
    });
  };

  // 改变页码
  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '物流中心',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  handleConfirm = (id: number, status: number) => {
    const params = {
      id,
      status,
      search: this.getQueryParams(),
    };

    this.fetchAction('change', params);
  };

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0 ? typeName : `logisticsCenterList/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const { pageIndex, pageSize } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      checkPerm,
      loading,
      screen,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card className="searchForm" bordered={false}>
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card className="tableList" bordered={false}>
          {
            checkPerm.add && (
              <div className="tableBtns">
                <Button
                  type="primary"
                  size="small"
                  className="smallButton marginB12"
                  onClick={this.handleAddLogisticsCenter}
                >
                  新建物流中心
                </Button>
              </div>
            )
          }
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableheight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </>
    );
  }
}

export default Form.create<LogisticsInfoProps>()(LogisticsInfoElem);
